#include "udpTracker.h"
#include "net/YUDPSocket.h"
#include "net/YAddress.h"
#include <vector>
#include <net/YBinaryStream.h>
#include <net/poll/SelectPoll.h>

UDPTracker::UDPTracker(const char* host, unsigned short port)
{
	mAddress = new YAddress(std::string(host), port);
	udpSocket = new YUDPSocket();
	udpSocket->setTimeout(3);
	udpSocket->onRead([&] (YUDPSocket* socket, YAddress* address, const char* buff, int len){
		if (address->getHost() == mAddress->getHost() && address->getPort() == mAddress->getPort())
		{
			this->onConnect( buff,  len);
		}
	});
	
}

void UDPTracker::connect()
{
	BinaryOutputStream buffer;

	buffer.writeLong( htonll( 0x41727101980));
	buffer.writeInt(0);
	buffer.writeInt(0x123);
	size_t size = udpSocket->sendTo(mAddress, (char*)buffer.data(), buffer.length());
	if (size == 0)
	{

	}


}
void UDPTracker::announce()
{

}
void UDPTracker::scrap()
{

}

void UDPTracker::onConnect(const char* buff, int len)
{
	BinaryInputStream buffer(buff, len);
	auto action = buffer.readInt();
	auto transaction_id = buffer.readInt();
	auto connection_id = buffer.readLong();

}
void UDPTracker::onAnnounce(const char* buff, int len)
{

}
void UDPTracker::onScrap(const char* buff, int len)
{

}

void UDPTracker::loop()
{
	SelectPoll pool;
	udpSocket->setIOPoll(&pool);
	while (true)
	{
		pool.wait(1);
	}
}